/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-03-23
 * Time: 21:10
 */
class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length,n = obstacleGrid[0].length;
        int[][] dp = new int[m][n];
        //初始化
        for(int i = 0; i < m && obstacleGrid[i][0] == 0; i++) {
           dp[i][0] = 1;
        }
        for(int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
           dp[0][j] = 1;
        }
       //初步判断
        if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) {
            return 0;
        }
        for(int i  = 1; i < m; i++) {
            for(int j = 1; j < n; j++) {
                if(obstacleGrid[i][j] == 1) {
                    continue;
                }
                dp[i][j] = dp[i-1][j]+dp[i][j-1];
            }
        }
        return dp[m-1][n-1];

    }

    //优化后
    public int uniquePathsWithObstacles1(int[][] obstacleGrid) {
        int m = obstacleGrid.length,n = obstacleGrid[0].length;
        int[][] dp = new int[m+1][n+1];
        dp[0][1] = 1;
        for(int i  = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                //注意映射关系
                if(obstacleGrid[i-1][j-1] == 0) {
                    dp[i][j] = dp[i-1][j]+dp[i][j-1];
                }
            }
        }
        return dp[m][n];
    }
}
